package com.kuang.allproject.service;

import com.kuang.allproject.entity.test;
import com.kuang.allproject.reposity.testReposity;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

@Service
public class testService {
    @Autowired
    private testReposity testReposity;

    private Integer successPersonNum = 0;
    private Integer successGoodsNum = 0;
    private Integer leftNum = 10;
    private Integer countNum = 1;
    /*修改注释*/

    private static CountDownLatch countDownLatch = new CountDownLatch(1000);

    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(1001);

    public void buy() throws InterruptedException, BrokenBarrierException {

        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(new UserAgent("测试商品",countNum),i + "").start();
            countDownLatch.countDown();
        }

        cyclicBarrier.await();
        long end = System.currentTimeMillis();

        System.out.println("用时 : " + (end - start));
        System.out.println("成功人数 : " + successPersonNum);
        System.out.println("售出商品数 : " + successGoodsNum);
        System.out.println("剩余商品数 : " + leftNum);

    }


    class UserAgent implements Runnable {

        private String goodsName;
        private Integer count;


        public UserAgent(String goodsName,Integer count) {
            this.goodsName = goodsName;
            this.count = count;
        }

        @SneakyThrows
        @Override
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (countDownLatch){
                //执行业务代码
                test test = testReposity.getOneByGoodsName(goodsName);
                Integer num = Integer.parseInt(test.getCouponName());

                if (num > 0){
                    Integer a = num - count;
                    test.setCouponName(a + "");
                    testReposity.saveAndFlush(test);
                    successGoodsNum++;
                    successPersonNum++;
                    leftNum--;
                    System.out.println(Thread.currentThread().getName());
                }
            }
            cyclicBarrier.await();
        }
    }
}
